package com.mxpio.erp.quality.controller;


import com.mxpio.erp.common.enums.NoticeStatusEnums;
import com.mxpio.erp.common.jpa.model.Notice;
import com.mxpio.erp.common.order.policy.NoticeContext;
import com.mxpio.erp.common.order.service.NoticeService;
import com.mxpio.erp.common.vo.OrderExcuteVo;
import com.mxpio.erp.common.quality.entity.MoInQualityOrder;
import com.mxpio.erp.common.quality.entity.MoInQualityOrderLine;
import com.mxpio.erp.common.quality.service.MoInQualityOrderService;
import com.mxpio.erp.common.workshop.entity.MoInNotice;
import com.mxpio.erp.quality.policy.DefaultInQualityOrderNoticePolicy;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.util.List;

@Tag(name = "MoInQualityOrderController", description = "生产入库验收单接口")
@RestController
@RequestMapping("/erp/quality/miqo/")
public class MoInQualityOrderController {

    @Autowired
    private MoInQualityOrderService service;
    
    @Autowired
    private NoticeService noticeService;
    
    @GetMapping("list")
    @Operation(summary = "生产入库验收单列表", description = "获取生产入库验收单列表（无分页）", method = "GET")
    public Result<List<MoInQualityOrder>> list(@Parameter(description="查询参数") Criteria criteria) throws UnsupportedEncodingException {
        List<MoInQualityOrder> moInQualityOrder = service.list(MoInQualityOrder.class, criteria);
        return Result.OK(moInQualityOrder);
    }

    @GetMapping("page")
    @Operation(summary = "生产入库验收单列表", description = "获取生产入库验收单列表（分页）", method = "GET")
    public Result<Page<MoInQualityOrder>> page(@Parameter(description="查询参数") Criteria criteria, @Parameter(description="每页条数")Integer pageSize, @Parameter(description="页号")Integer pageNo) throws UnsupportedEncodingException {
        Pageable page = PageRequest.of(pageNo-1, pageSize);
        Page<MoInQualityOrder> moInQualityOrder = service.listPage(MoInQualityOrder.class, page, criteria);
        return Result.OK(moInQualityOrder);
    }

    @GetMapping("list/{noticeNo}")
    @Operation(summary = "根据noticeNo获取生产入库验收单", description = "根据noticeNo获取生产入库验收单", method = "GET")
    public Result<MoInQualityOrder> getById(@Parameter(description="业务单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
        MoInQualityOrder moInQualityOrder = service.getById(MoInQualityOrder.class, noticeNo);
        return Result.OK(moInQualityOrder);
    }

    @RequestMapping("save")
    @Operation(summary = "保存生产入库验收单", description = "保存生产入库验收单", method = "POST")
    public Result<MoInQualityOrder> save(@RequestBody MoInQualityOrder notice) {
        service.save(notice,new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if(o instanceof MoInQualityOrderLine){
                    MoInQualityOrder moInQualityOrder = context.getParent();
                    ((MoInQualityOrderLine) o).setNoticeNo(moInQualityOrder.getNoticeNo());
                }
                return true;
            }
        });
        return Result.OK(notice);
    }
    
    @RequestMapping("excute/{noticeNo}")
    @Operation(summary = "通知单执行", description = "通知单执行")
    public Result<Object> excute(@PathVariable(name = "noticeNo", required = true) String noticeNo, 
    		@RequestBody OrderExcuteVo orderExcuteVo) {
    	MoInQualityOrder notice = service.getById(MoInQualityOrder.class, noticeNo);
        if (notice.getNoticeStatus().equals(NoticeStatusEnums.NoticeStatus.CONFIRM.getStatusCode())){
            return Result.error("单据状态已发生变化，已确认状态单据不允许重复确认！");
        }
    	NoticeContext context = noticeService.execute(notice, new DefaultInQualityOrderNoticePolicy(orderExcuteVo.getLines()));
    	if(CollectionUtils.isEmpty(context.getErrors())) {
    		return Result.OK();
    	}else {
    		return Result.error(context.getErrors().get(0));
    	}
    }


    @DeleteMapping("remove/{noticeNos}")
    @Operation(summary = "根据noticeNo删除生产入库验收单", description = "删除生产入库验收单", method = "DELETE")
    public Result<MoInQualityOrder> remove(@Parameter(description="业务单号，多个单号用英文逗号分隔") @PathVariable(name = "noticeNos", required = true) String noticeNos) {
        String[] noticeNo = noticeNos.split(",");
        for(String key : noticeNo){
            service.delete(MoInQualityOrder.class, key);
        }
        return Result.OK();
    }
    
    @PutMapping("reject/{noticeNo}")
    @Operation(summary = "拒绝通知单", description = "拒绝通知单", method = "PUT")
    public Result<? extends Notice> close(@Parameter(description="通知单号") @PathVariable(name = "noticeNo", required = true) String noticeNo) {
    	MoInQualityOrder moInQualityOrder = service.getById(MoInQualityOrder.class,noticeNo);
    	return noticeService.updateNoticeStatus(moInQualityOrder, NoticeStatusEnums.NoticeStatus.REJECT);
    }

    @GetMapping("listbynos/{noticeNos}")
    @Operation(summary = "根据noticeNos获取对应生产入库验收单及明细", description = "根据noticeNos获取生产入库验收单及明细", method = "GET")
    public Result<List<MoInQualityOrder>> getByIds(@PathVariable(name = "noticeNos", required = true) String noticeNos) {
        return service.listByIds(noticeNos);
    }

}
